import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import authService from '@/services/authService'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || null)
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  
  const isAuthenticated = computed(() => !!token.value)
  
  const setAuth = (authData) => {
    token.value = authData.token
    user.value = {
      id: authData.userId,
      username: authData.username,
      email: authData.email,
      eoaAddress: authData.eoaAddress,
      role: authData.role
    }
    localStorage.setItem('token', authData.token)
    localStorage.setItem('user', JSON.stringify(user.value))
  }
  
  const clearAuth = () => {
    token.value = null
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }
  
  const register = async (userData) => {
    const response = await authService.register(userData)
    if (response.success) {
      setAuth(response.data)
    }
    return response
  }
  
  const login = async (credentials) => {
    const response = await authService.login(credentials)
    if (response.success) {
      setAuth(response.data)
    }
    return response
  }
  
  const logout = () => {
    clearAuth()
  }
  
  return {
    token,
    user,
    isAuthenticated,
    register,
    login,
    logout,
    setAuth,
    clearAuth
  }
})




